#include "abstractvmodel.h"
#include <QDebug>
#include <QTextCodec>
#include <QColor>

AbstractVModel::AbstractVModel(int tableIndex, int subTableIndex, QObject *parent):QAbstractTableModel(parent)
{
    _tIndex = tableIndex;
    _subIndex = subTableIndex;
    db = g_DataSet.FindVTable(tableIndex,subTableIndex);

    char fls[4096*2] = {0};
    db->GetTableFieldPChar(fls);
    QString fields(fls);
    _fieldList = fields.split(",");
    _fieldList.removeAt(1);

    unsigned int size = db->GetRecordCount();

    codec = QTextCodec::codecForName("GBK");
    _posList.reserve(size);

    for( unsigned int i = 0; i < size; i++ )
    {
        _posList.insert(i,i);
        //append(i);
    }
}

AbstractVModel::~AbstractVModel()
{

}

int AbstractVModel::rowCount(const QModelIndex &parent) const
{
    return _posList.size();
}

int AbstractVModel::columnCount(const QModelIndex &parent) const
{
    return _fieldList.size();
}

QVariant AbstractVModel::data(const QModelIndex &index, int role) const
{
    int pos = index.row();
    int col = index.column();
    char buf[256] = {0};

    switch (role) {
    case Qt::TextAlignmentRole:
    {
        return Qt::AlignCenter;
    }
    case Qt::DisplayRole:
    case SortRole:
    {
        if( col == 0 )
            return index.row();

        if( _fieldList[col].contains("_0_"))
        {
            QStringList poss = _fieldList[col].split("_0_");

            db->GetSValue(pos,poss[0].toStdString().c_str(),0,poss[1].toStdString().c_str(),buf, sizeof(buf));
        }
        else
        {
            db->GetValue(pos,_fieldList[col].toStdString().c_str(),buf,sizeof(buf));
        }


        if( strlen(buf) == 0 )
            return QVariant();

//        QRegExp re("\\d*");
//        if( re.exactMatch(QString(buf)) )
//          return QString(buf).toInt();
        return codec->toUnicode(buf);

    }
    case Qt::BackgroundRole:
    {
        if( db->IsDeleted(pos) )
            return QVariant(QColor(Qt::gray).lighter());
    }
    default:
        break;
    }

    return QVariant();
}

QVariant AbstractVModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Vertical) return QString::number(section);
    if (role != Qt::DisplayRole) return QVariant();

    if( section < _fieldList.size() )
        return _fieldList[section];
    return QVariant();
}

void AbstractVModel::append(int ipos)
{
    beginInsertRows(QModelIndex(),_posList.count(),_posList.count());

    _posList.insert(ipos,ipos);

    endInsertRows();
}

void AbstractVModel::onDataSetUpdate(MSGBUF *msg)
{
    QModelIndex topIndex = createIndex(0,0);
    QModelIndex bottomIndex = createIndex(0,_fieldList.size()-1);
    emit dataChanged(topIndex,bottomIndex);
}


